package com.tgy.files.service.impl;

import cn.hutool.core.util.StrUtil;
import com.mongodb.MongoGridFSException;
import com.mongodb.client.gridfs.GridFSBucket;
import com.tgy.pojo.BlogArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.annotation.Resource;
import java.io.*;
import java.util.HashMap;
import java.util.Map;


@Component
public class HtmlService {

    @Resource
    private GridFSBucket gridFSBucket;

    @Value("${freemarker.html.article}")
    private String articlePath;
    @Value("${freemarker.html.target}")
    private String target;

    /**
     * 生成文章到指定文件夹下
     * @param articleVo
     * @throws Exception
     */
    public void createArticleHTML(BlogArticle articleVo) throws Exception {

        Configuration cfg = new Configuration(Configuration.getVersion());
        String classpath = this.getClass().getResource("/").getPath();
        cfg.setDirectoryForTemplateLoading(new File(classpath + "templates"));
        Template template = cfg.getTemplate("detail.ftl", "utf-8");

        // 获得文章的详情数据
        // BlogArticle articleVo = sysArticleService.getArticleById(articleId);
        Map<String, Object> map = new HashMap<>();
        map.put("article", articleVo);

        //存放html的文件夹是否存在，不存在则创建
        File tempDic = new File(articlePath);
        if (!tempDic.exists()) {
            tempDic.mkdirs();
        }

        //直接将生成好的文件写到对应的地方
        String path = articlePath + File.separator + articleVo.getId() + ".html";
        //输出成html文件
        Writer out = new FileWriter(path);
        //将数据填充进模板文件
        template.process(map, out);
        out.close();
    }

    /**
     * 生成文章到GridFS
     */
    public String createArticleHTMLToGridFS(BlogArticle articleVo) throws Exception {
        Configuration cfg = new Configuration(Configuration.getVersion());
        File directory = new File("src/main/resources");
        // String classpath = directory.getCanonicalPath();
        String classpath = this.getClass().getResource("/").getPath();
        try {
            cfg.setDirectoryForTemplateLoading(new File(classpath + "/templates"));
        }catch (FileNotFoundException e){
            cfg.setDirectoryForTemplateLoading(new File(target + "/templates"));
            e.printStackTrace();
        }
        Template template = cfg.getTemplate("detail.ftl", "utf-8");
        // 获得文章的详情数据
        // BlogArticle articleVo = sysArticleService.getArticleById(articleId);
        Map<String, Object> map = new HashMap<>();
        map.put("article", articleVo);

        //htmlContent就是生成的html代码字符串
        String htmlContent = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
//        System.out.println(htmlContent);
        //将字符串转换成流
        InputStream inputStream = IOUtils.toInputStream(htmlContent);
        //上传到GridFS
        ObjectId fileId = gridFSBucket.uploadFromStream(articleVo.getId() + ".html",inputStream);
        return fileId.toString();
    }

    /**
     * 下载html
     * @param articleId         文章ID
     * @param articleMongoId    articleMongoId
     */
    public Integer download(String articleId, String articleMongoId)
            throws Exception {
        // 拼接最终文件的保存的地址
        String path = articlePath + File.separator + articleId + ".html";
        // 获取文件流，定义存放的位置和名称
        File file = new File(path);
        // 创建输出流
        OutputStream outputStream = new FileOutputStream(file);
        // 执行下载
        gridFSBucket.downloadToStream(new ObjectId(articleMongoId), outputStream);
        return HttpStatus.OK.value();
    }

    /**
     * 删除html
     * @param articleId     文章ID
     */
    public Integer delete(String articleId,String articleMongoId) {
        // 拼接最终文件的保存的地址
        String path = articlePath + File.separator + articleId + ".html";
        // 获取文件流，定义存放的位置和名称
        File file = new File(path);
        // 删除文件
        file.delete();
        try {
            if (StrUtil.isNotBlank(articleMongoId)){
                gridFSBucket.delete(new ObjectId(articleMongoId));
            }
        }catch (MongoGridFSException e){
            String message = e.getMessage();
            if (!message.contains("No file found with the id")){
                throw new MongoGridFSException(message);
            }else {
                e.printStackTrace();
            }
        }
        return HttpStatus.OK.value();
    }

}
